from django.db import models
from django.conf import settings
from django.core.urlresolvers import reverse
import re

class Category(models.Model):
    slug = models.SlugField(db_index=True, unique=True)
    name = models.CharField(max_length=25)
    active = models.BooleanField(default=True)
    ordering = models.PositiveIntegerField(default=1)

    class Meta:
        ordering = ['ordering']
        verbose_name_plural = 'Categories'

    def __unicode__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('gallery_category', args=[self.slug])

class Gallery(models.Model):
    slug = models.SlugField(db_index=True, unique=True)
    name = models.CharField(max_length=50)
    ordering = models.PositiveIntegerField(default=1)
    categories = models.ManyToManyField(Category, blank=True)

    class Meta:
        ordering = ['ordering']
        verbose_name_plural = 'Galleries'

    def contents(self):
        contents = []

        contents.extend(self.gallery_gallery_image.all())
        contents.extend(self.gallery_gallery_video.all())

        return sorted(contents, key=lambda x: x.ordering)

    @property
    def cover_item(self):
        contents = []

        contents.extend(self.gallery_gallery_image.all()[:1])
        contents.extend(self.gallery_gallery_video.all()[:1])

        return sorted(contents, key=lambda x: x.ordering)[:1].pop()

    def __unicode__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('gallery_gallery', args=[self.slug])

class GalleryImage(models.Model):
    alt_text = models.CharField(blank=True, max_length=250)
    image = models.FileField(upload_to='gallery/')
    thumbnail_image = models.FileField(upload_to='gallery/thumbnail/')
    ordering = models.PositiveIntegerField(default=1)
    gallery = models.ForeignKey(Gallery, related_name='gallery_gallery_image')

    @property
    def type(self):
        return 'image'

    class Meta:
        ordering = ['ordering']

    def __unicode__(self):
        return self.alt_text

class GalleryVideo(models.Model):
    name = models.CharField(blank=False, max_length=100)
    url = models.CharField(blank=False, max_length=250)
    image = models.FileField(upload_to='video/')
    thumbnail_image = models.FileField(upload_to='video/thumbnail/')
    ordering = models.PositiveIntegerField(default=1)
    gallery = models.ForeignKey(Gallery, related_name='gallery_gallery_video')

    @property
    def type(self):
        return 'video'

    @property
    def video_id(self):
        matches = re.search('vimeo.com/([0-9]+)', self.url)

        return matches.group(1)

    class Meta:
        ordering = ['ordering']

    def __unicode__(self):
        return self.name
